#    Copyright 2012 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings, random
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
from django.template import Context, loader
import djangoproject.settings
import _mysql as mysql
from django import forms
import django
import djangoproject
from models import *
import COOPIP_Ajax
import COOPIP_Misc
import COOPIP_Form, COOPIP_DynamicTemplate, COOPIP_Authentication, COOPIP_FormRevenueProtection, COOPIP_FormNetworkDevice






def MainMenu(request):
    import datetime
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, ['COOPIP_Editor_Technology'])
    if(not Permission):
        t = loader.get_template('/opt/coopip/djangoproject/templates/networkdevicemainmenu.html')
        c = Context({'LoginStatus': LoginStatus, 'Permission': Permission})
    form=COOPIP_Form.LoginForm()
    t = loader.get_template('/opt/coopip/djangoproject/templates/networkdevicemainmenu.html')
    c = Context({'LoginStatus': LoginStatus, 'form': form, 'Permission': Permission})
    return HttpResponse(t.render(c))


def NetworkDeviceNoPermission():
    t = loader.get_template('/opt/coopip/djangoproject/templates/networkdevicemainmenu.html')
    c = Context({'LoginStatus': LoginStatus, 'Permission': Permission})
    return HttpResponse(t.render(c))

def AddEdit(request):
    import datetime
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, ['COOPIP_Editor_Technology'])
    if(not Permission):
        t = loader.get_template('/opt/coopip/djangoproject/templates/networkdevicemainmenu.html')
        c = Context({'LoginStatus': LoginStatus, 'Permission': Permission})
    SpecialBuildFormDataDict={'request': request}
    form=COOPIP_Form.BuildDynamicForm(request, 'NetworkDeviceAddEdit', SpecialBuildFormDataDict)
    networkDevice=COOPIP_FormNetworkDevice.ProcessNetworkDeviceAddEditForm(form, Username, request)
    
    #Now, rebuild the form in case a new network device was created, so that it will be selected
    if(networkDevice):
        SpecialBuildFormDataDict['NetworkDevice']=networkDevice
    form=COOPIP_Form.BuildDynamicForm(request, 'NetworkDeviceAddEdit', SpecialBuildFormDataDict)
    NetworkDevicePorts=NetworkDevicePort.objects.filter(NetworkDevice=networkDevice)
    form=COOPIP_FormNetworkDevice.PopulateNetworkDeviceAddEditForm(form, networkDevice)
    COOPIP_DynamicTemplate.UpdateNetworkDeviceAddEditTemplate(NetworkDevicePorts=NetworkDevicePorts, Username=Username)
    t = loader.get_template('/opt/coopip/djangoproject/templates/dynamic_networkdeviceaddedit' + Username + '.html')
    c = Context({'LoginStatus': LoginStatus, 'form': form, 'Permission': Permission})
    return HttpResponse(t.render(c))

def UpdateDiagram(Report):
    import os, subprocess, shlex
    os.chdir()
    NetworkDeviceDiagramPath=''
    Output=open('tempfile.dot', 'w')
    Output.write('graph g1 {')
    Output.writelines('\n'.join(Input))
    Output.write('}')
    subprocess.call(shlex.split('dot tempfile.dot -Tpng -o NetworkDeviceDiagram.png'))

def GetNodeString(Name, Label=None):
    Name=str(Name)
    if not Label:
        return Name
    ReturnString=Name + '[label=\"' + Label + '\"]'
    return ReturnString

def GetEdgeString(Source, Destination, Label=None):
    Source=str(Source)
    Destination=str(Destination)
    if Label:
        Label=str(Label)
        ReturnString=Source + '--' + Destination + '[label=\"' + Label + '\"]'
    else:
        ReturnString=Source + '--' + Destination
    return ReturnString


def ShowDiagram(request):
    import datetime
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, ['COOPIP_Editor_Technology'])
    if(not Permission):
        t = loader.get_template('/opt/coopip/djangoproject/templates/networkdevicemainmenu.html')
        c = Context({'LoginStatus': LoginStatus, 'Permission': Permission})
    form=COOPIP_Form.LoginForm()
    networkDevice=COOPIP_FormNetworkDevice.ProcessNetworkDeviceShowDiagramForm(form, Username, request)
    Report=[]
    Report.append(GetGraphVizNode(Name=networkDevice.id, Label=networkDevice.Name))
    ConnectedDevices=networkDevice.GetDirectlyConnectedDeviceList()
    for i in ConnectedDevices:
        Report.append(GetNodeString(Name=i.id, Label=i.Name))
    PortConnections=networkDevice.GetConnectionList()
    for i in PortConnections:
        SourcePort, DestinationPort=i
        Label=SourcePort.Name + ' -- ' + DestinationPort.Name
        Report.append(GetEdgeString(Source=networkDevice.id, Destination=DestinationPort.NetworkDevice.id, Label=Label))
    
    
    t = loader.get_template('/opt/coopip/djangoproject/templates/networkdeviceshowdiagram.html')
    c = Context({'LoginStatus': LoginStatus, 'form': form, 'Permission': Permission})
    return HttpResponse(t.render(c))

def NetworkDevicePortConnectionAddEdit(request):
    #FIXME Stub Function
    import datetime
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, ['COOPIP_Editor_Technology'])
    if(not Permission):
        t = loader.get_template('/opt/coopip/djangoproject/templates/networkdevicemainmenu.html')
        c = Context({'LoginStatus': LoginStatus, 'Permission': Permission})
    form=COOPIP_Form.LoginForm()
    t = loader.get_template('/opt/coopip/djangoproject/templates/networkdevicemainmenu.html')
    c = Context({'LoginStatus': LoginStatus, 'form': form, 'Permission': Permission})
    return HttpResponse(t.render(c))


def NetworkDeviceReport(request):
    #FIXME Stub Function
    import datetime
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, ['COOPIP_Editor_Technology'])
    if(not Permission):
        t = loader.get_template('/opt/coopip/djangoproject/templates/networkdevicemainmenu.html')
        c = Context({'LoginStatus': LoginStatus, 'Permission': Permission})
    form=COOPIP_Form.LoginForm()
    t = loader.get_template('/opt/coopip/djangoproject/templates/networkdevicemainmenu.html')
    c = Context({'LoginStatus': LoginStatus, 'form': form, 'Permission': Permission})
    return HttpResponse(t.render(c))

def NetworkDeviceConnectionReport(request):
    #FIXME Stub Function
    import datetime
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, ['COOPIP_Editor_Technology'])
    if(not Permission):
        t = loader.get_template('/opt/coopip/djangoproject/templates/networkdevicemainmenu.html')
        c = Context({'LoginStatus': LoginStatus, 'Permission': Permission})
    form=COOPIP_Form.LoginForm()
    t = loader.get_template('/opt/coopip/djangoproject/templates/networkdevicemainmenu.html')
    c = Context({'LoginStatus': LoginStatus, 'form': form, 'Permission': Permission})
    return HttpResponse(t.render(c))






